package com.hzqy.service.ift;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.XpYunUtil;
import com.hzqy.persistence.dao.content.ContentDao;
import com.hzqy.web.vo.CmContentVo;
import com.hzqy.web.vo.HotelUserNeedsVo;
import com.hzqy.web.vo.PmsOrgVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class XpYunServiceBean {

	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	final private int CATALOG_KFFW = 855;//客房服务
	final private int CATALOG_DCFW = 857;//点餐服务
	final private int CATALOG_GWFW = 859;//购物服务
	final private int CATALOG_TSJY = 861;//投诉建议

	@Resource
	private ContentDao contentDao;

	public Map<String, Object> addPrinters(String sn) {
		Map<String, Object> resultMap = new HashMap<>();

		JSONObject params = new JSONObject();
		params.put("user", XpYunUtil.USER);
		params.put("timestamp", String.valueOf(System.currentTimeMillis()));
		params.put("sign", DigestUtils.sha1Hex(XpYunUtil.USER + XpYunUtil.USER_KEY + params.get("timestamp")));
		params.put("debug", "0");

		JSONArray items = new JSONArray();
		JSONObject item = new JSONObject();
		item.put("sn", sn);
		item.put("name", "康德测试打印机");
		items.add(item);

		params.put("items", items);

		String param = JSONObject.toJSONString(params);
		String api_url = "https://open.xpyun.net/api/openapi/xprinter/addPrinters";
		LOG.debug("芯烨云API (addPrinters) url: " + api_url);
		LOG.debug("芯烨云API (addPrinters) params: " + param);
		long t1 = System.currentTimeMillis();
		Map<String, String> requestMap = XpYunUtil.post(api_url, param);
		LOG.debug("芯烨云API (addPrinters) 请求结果: " + requestMap + " 耗时: " + (System.currentTimeMillis() - t1) + "ms.");

		resultMap.put("requestMap", requestMap);
		if ("1".equals(requestMap.get("success"))) {
			JSONObject resultJson = JSONObject.parseObject(requestMap.get("msg"));
			if ("0".equals(resultJson.getInteger("code"))) {
				resultMap.put("success", 1);
				resultMap.put("msg", "接口调用成功!");
			} else {
				resultMap.put("success", -2);
				resultMap.put("msg", "接口返回code有误！ msg: " + resultJson.getString("msg"));
			}
		} else {
			resultMap.put("success", -1);
			resultMap.put("msg", "接口请求状态码有误！ msg: " + requestMap.get("msg"));
		}

		return resultMap;
	}

	public Map<String, Object> setVoiceType(int voiceType,String sn) {
		Map<String, Object> resultMap = new HashMap<>();

		JSONObject params = new JSONObject();
		params.put("user", XpYunUtil.USER);
		params.put("timestamp", String.valueOf(System.currentTimeMillis()));
		params.put("sign", DigestUtils.sha1Hex(XpYunUtil.USER + XpYunUtil.USER_KEY + params.get("timestamp")));
		params.put("debug", "0");

		params.put("sn", sn);
		params.put("voiceType", voiceType);// 声音类型： 0真人语音（大） 1真人语音（中） 2真人语音（小） 3 嘀嘀声 4 静音


		String param = JSONObject.toJSONString(params);
		String api_url = "https://open.xpyun.net/api/openapi/xprinter/setVoiceType";
		LOG.debug("芯烨云API (setVoiceType) url: " + api_url);
		LOG.debug("芯烨云API (setVoiceType) params: " + param);
		long t1 = System.currentTimeMillis();
		Map<String, String> requestMap = XpYunUtil.post(api_url, param);
		LOG.debug("芯烨云API (setVoiceType) 请求结果: " + requestMap + " 耗时: " + (System.currentTimeMillis() - t1) + "ms.");

		resultMap.put("requestMap", requestMap);
		if ("1".equals(requestMap.get("success"))) {
			JSONObject resultJson = JSONObject.parseObject(requestMap.get("msg"));
			if ("0".equals(resultJson.getInteger("code"))) {
				resultMap.put("success", 1);
				resultMap.put("msg", "接口调用成功!");
			} else {
				resultMap.put("success", -2);
				resultMap.put("msg", "接口返回code有误！ msg: " + resultJson.getString("msg"));
			}
		} else {
			resultMap.put("success", -1);
			resultMap.put("msg", "接口请求状态码有误！ msg: " + requestMap.get("msg"));
		}

		return resultMap;
	}

	public Map<String, Object> printHotelUserNeedsVo(HotelUserNeedsVo hotelUserNeedsVo) {
		HashMap<String,String> resultMap = voToString(hotelUserNeedsVo);
		String content = resultMap.get("printContent");
		String sn = resultMap.get("sn");
		Map<String, Object> map = print(content,sn);//02H7F1T4TR30548
		return map;
	}

	public Map<String, Object> print(String content,String sn) {
		Map<String, Object> resultMap = new HashMap<>();

		JSONObject params = new JSONObject();
		params.put("user", XpYunUtil.USER);
		params.put("timestamp", String.valueOf(System.currentTimeMillis()));
		params.put("sign", DigestUtils.sha1Hex(XpYunUtil.USER + XpYunUtil.USER_KEY + params.get("timestamp")));
		params.put("debug", "0");

		params.put("sn", sn);
		params.put("copies", 1);
		params.put("mode", 1);

		params.put("content", content);

		String param = JSONObject.toJSONString(params);
		String api_url = "https://open.xpyun.net/api/openapi/xprinter/print";
		LOG.debug("芯烨云API (print) url: " + api_url);
		LOG.debug("芯烨云API (print) params: " + param);
		long t1 = System.currentTimeMillis();
		String requestMap = XpYunUtil.doPostJSON(api_url, param,null);
		LOG.debug("芯烨云API (print) 请求结果: " + requestMap + " 耗时: " + (System.currentTimeMillis() - t1) + "ms.");

		JSONObject resultJson = JSONObject.parseObject(requestMap);
		if ("0".equals(resultJson.getString("code"))) {
			resultMap.put("success", 1);
			resultMap.put("msg", "接口调用成功!");
		} else {
			resultMap.put("success", -2);
			resultMap.put("msg", "接口返回code有误！ msg: " + resultJson.getString("msg"));
		}

		return resultMap;
	}

	public Map<String, Object> playVoice(String sn) {
		Map<String, Object> resultMap = new HashMap<>();

		JSONObject params = new JSONObject();
		params.put("user", XpYunUtil.USER);
		params.put("timestamp", String.valueOf(System.currentTimeMillis()));
		params.put("sign", DigestUtils.sha1Hex(XpYunUtil.USER + XpYunUtil.USER_KEY + params.get("timestamp")));
		params.put("debug", "0");

		params.put("sn", sn);
		params.put("payType", 41);// 	支付方式：
		// 取值范围41~55：
		// 支付宝 41、微信 42、云支付 43、银联刷卡 44、银联支付 45、会员卡消费 46、会员卡充值 47、翼支付 48、成功收款 49、嘉联支付 50、壹钱包 51、京东支付 52、快钱支付 53、威支付 54、享钱支付 55

		params.put("payMode", 60);// 	支付与否：
		// 取值范围59~61：
		// 退款 59 到账 60 消费 61。
		params.put("money", 11);// 	支付金额：
		// 最多允许保留2位小数。

		String param = JSONObject.toJSONString(params);
		String api_url = "https://open.xpyun.net/api/openapi/xprinter/playVoice";
		LOG.debug("芯烨云API (playVoice) url: " + api_url);
		LOG.debug("芯烨云API (playVoice) params: " + param);
		long t1 = System.currentTimeMillis();
		Map<String, String> requestMap = XpYunUtil.post(api_url, param);
		LOG.debug("芯烨云API (playVoice) 请求结果: " + requestMap + " 耗时: " + (System.currentTimeMillis() - t1) + "ms.");

		resultMap.put("requestMap", requestMap);
		if ("1".equals(requestMap.get("success"))) {
			JSONObject resultJson = JSONObject.parseObject(requestMap.get("msg"));
			if ("0".equals(resultJson.getInteger("code"))) {
				resultMap.put("success", 1);
				resultMap.put("msg", "接口调用成功!");
			} else {
				resultMap.put("success", -2);
				resultMap.put("msg", "接口返回code有误！ msg: " + resultJson.getString("msg"));
			}
		} else {
			resultMap.put("success", -1);
			resultMap.put("msg", "接口请求状态码有误！ msg: " + requestMap.get("msg"));
		}

		return resultMap;
	}


    public static void main(String[] args) {
        //new XpYunServiceBean().addPrinters();
		//new XpYunServiceBean().setVoiceType(4);
		//new XpYunServiceBean().playVoice();



		// <BR>：换行符（同一行有闭合标签(如 </C>)则应放到闭合标签前面, 连续两个换行符<BR><BR>可以表示加一空行）
		// <L></L>：左对齐
//		<C></C>：居中对齐
//		<R></R>：右对齐
//		<N></N>：字体正常大小
//		<HB></HB>：字体变高一倍
//		<WB></WB>：字体变宽一倍
//		<B></B>：字体放大一倍
//		<CB></CB>：字体放大一倍居中
//		<HB2></HB2>：字体变高二倍
//		<WB2></WB2>：字体变宽二倍
//		<B2></B2>：字体放大二倍
//		<BOLD></BOLD>：字体加粗
//		<LOGO></LOGO>：LOGO图片（标签内容是图片Base64格式字符串, 暂未开放）
//		<QR></QR>：二维码（标签内容是二维码值, 最大不能超过256个字符, 单个订单最多只能打印一个二维码）。
//		二维码宽度设置：可以通过 <QR> 标签名称自定义，如 <QR180> 表示宽度为180，不指定默认为132，
//		最小值为80，最大值为185
//		<BARCODE></BARCODE>：条形码（标签内容是条形码值）

		String printContent = "" +
				// "<LOGO>" + XpYunUtil.ImageToBase64ByLocal("D:\\IdeaProjects\\gd_hqjc_web\\src\\main\\webapp\\PIC\\model\\commons\\hotel_02\\imgs\\info\\back_focus.png").replaceAll("\\r\\n", "") + "</LOGO>\r\n" +
 "<HB><C> **# 测试酒店**</C></HB>\n"
//				"................................\n" +
//				"<B><C>----货到付款----</C></B>\n" +
//				"<BOLD><C>XPYUN SDK 打印测试</C></BOLD>\n" +
//				"下单时间：2020-09-27 16:20:02\n" +
//				"订单编号：123\n" +
//				"<C>---物品维修---</C><HB> \n" +
//				"加裤子一件\n" +
//				"</HB>\n" +
//				"................................\n" +
//				"服务时间：2020-02-02 00:02:02\n" +
//				"********************************<HB>\n" +
//				"订单总价：￥120\n" +
//				"房间号：1001\n" +
//				"订单备注：无\n" +
//				"</HB><B><C> ** 完 **</C></B>"
			;

		// printContent = "<LOGO><LC>GyoAPwAAAAAAAAAAAAAAAAABAQMHDgwZGBgwMBAAIDYGBAyMjASEBgMDAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKGyoAPwAAAAAAAAAAAAEAAAyc2PBgxYcCAkKDAQAAAABAcHB4cHIDB/7///9/f38fH8//Xx8fDw8PRyEAAAAAAAAAAAAKGyoAPwAIDA8PREjAgAAAAQEHj8cAAAEBAULCwAAAAQcAAAEHAzj8/z+f/////////////////////P4AAAAHD///fx8KGyoAPwAAAADMREZicmLy//35+f3//z8/Pjw4YIAAhAgINPjzxv///vbkwc/98///+vz48ODQ/OAAAQ8DH38///////8KGyoAPwAAAAAAAAAAAAAA8PDg4ODAwMAIAAAgQICgIECAAIAMOGDAAAAQwIBggPgAAABg8HBAQEDAwMDD/vz+/PDAwIAKGyoAPwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK</LOGO>" + printContent;


		new XpYunServiceBean().print(printContent,"02H7F1T4TR30548");
		//Map<String, Object> map = new HashMap<>();
		//map.put("sss", XpYunUtil.ImageToBase64ByLocal("D:\\IdeaProjects\\gd_hqjc_web\\src\\main\\webapp\\PIC\\model\\commons\\hotel_02\\imgs\\info\\back_focus.png").replaceAll("\\r\\n", ""));
		//System.out.println(JSONObject.toJSONString(map));

		// System.out.println(XpYunUtil.ImageToBase64ByLocal("D:\\IdeaProjects\\gd_hqjc_web\\src\\main\\webapp\\PIC\\model\\commons\\hotel_02\\imgs\\info\\back_focus.png"));
    }

	//vo转String 用于打印机输出
	public HashMap<String,String> voToString(HotelUserNeedsVo hotelUserNeedsVo){
		HashMap<String,String> resultMap = new HashMap<String,String>();
		String printContent = "";
		String sn = "";
		Date date = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowTime=sf.format(date);
		String fwType = "";
		int f_ccc_catalogid = 0;
		switch (hotelUserNeedsVo.getF_hsn_type()){
			case 1:
				fwType = "房间清扫";
				f_ccc_catalogid = CATALOG_KFFW;
				break;
			case 2:
				fwType = "添加物品";
				f_ccc_catalogid = CATALOG_KFFW;
				break;
			case 3:
				fwType = "物品维修";
				f_ccc_catalogid = CATALOG_KFFW;
				break;
			case 4:
				fwType = "投诉建议";
				f_ccc_catalogid = CATALOG_TSJY;
				break;
			case 5:
				fwType = "闪电退房";
				f_ccc_catalogid = CATALOG_KFFW;
				break;
			case 6:
				fwType = "洗衣服务";
				f_ccc_catalogid = CATALOG_KFFW;
				break;
			case 7:
				fwType = "叫醒服务";
				f_ccc_catalogid = CATALOG_KFFW;
				break;
			case 8:
				fwType = "叫车服务";
				f_ccc_catalogid = CATALOG_KFFW;
				break;
			case 11:
				fwType = "客房送餐";
				f_ccc_catalogid = CATALOG_DCFW;
				break;
			case 12:
				fwType = "预约发票";
				f_ccc_catalogid = CATALOG_KFFW;
				break;
			case 13:
				fwType = "添物报修";
				f_ccc_catalogid = CATALOG_KFFW;
				break;
			case 14:
				fwType = "购物服务";
				f_ccc_catalogid = CATALOG_GWFW;
				break;
			default:
				fwType = "客房服务";
				f_ccc_catalogid = CATALOG_KFFW;
				break;
		}
		String fwTime = "";
		if("1".equals(hotelUserNeedsVo.getF_hsn_zxtype())){
			fwTime = "立即";
		}else{
			fwTime = hotelUserNeedsVo.getF_hsn_zxdate();
		}

		String fwMoney = "";
		if(hotelUserNeedsVo.getF_hsn_price()==null){
			fwMoney = "免费";
		}else{
			fwMoney = "￥"+new DecimalFormat("0.0").format(hotelUserNeedsVo.getF_hsn_price());
		}

		String fwRemarks = hotelUserNeedsVo.getF_hsn_remarks()==null?"无":hotelUserNeedsVo.getF_hsn_remarks();

		printContent = "" +
				"<HB><C> **# "+hotelUserNeedsVo.getF_hsn_orgName()+ "**</C></HB>\r\n"+
				"................................\r\n" +
				"下单时间："+nowTime+"\r\n" +
				"订单编号："+hotelUserNeedsVo.getF_hsn_id()+"\r\n" +
				"***********客房服务*************\r\n<C>---"+fwType+"---</C><HB> \n" +
				hotelUserNeedsVo.getF_hsn_detail()+ "\r\n" +
				"</HB>\n" +
				"................................\r\n" +
				"服务时间："+fwTime+"\r\n" +
				"********************************<HB>\n" +
				"订单总价："+fwMoney+"\r\n" +
				"房间号："+hotelUserNeedsVo.getF_hsn_roonNum()+"\r\n" +
				"订单备注："+fwRemarks+"\r\n" +
				"</HB><B><C> ** 完 **</C></B>\r\n" +
				"\r\n" +
				"\r\n"
		;
		resultMap.put("printContent",printContent);

		//获取sn
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("f_ccc_catalogid", f_ccc_catalogid);
		map.put("f_cc_status",1);
		map.put("f_cc_companyid", hotelUserNeedsVo.getF_hsn_orgId()+"");
		map.put("firstResult", 0);
		map.put("maxResults", 1);
		List<CmContentVo> results = contentDao.selectBindContent(map);
		if(!results.isEmpty()){
			sn = results.get(0).getF_cc_obligate1();
		}
		resultMap.put("sn",sn);
		return resultMap;
	}

}
